/**
 * 报文助手函数
 */
import {
	MSG_HEAD,
	MSG_CODE,
	RES_CODE
} from '@/config.js'

import store from '@/store'

/**
 * @param {int} code 操作码
 * @param {array} data 参数
 * 报文校验和
 */
export function sumCheck(code, data) {
	let params = [MSG_HEAD, code, data.length].concat(data)
	let sum = 0
	params.forEach(val => {
		sum += val
	})
	return sum & 0xff
}

/**
 * 返回校验
 */
export function resCheck(code) {
	let resCode = code + RES_CODE
	let len = 1
	let msg = [MSG_HEAD, resCode, len, 1, sumCheck(resCode, [1])]
	return msg
}

/**
 * 自定义模式检验
 */

export function msgsCheck(code, data) {
	let resCode = code + RES_CODE
	let len = data.length + 1
	let msg = [MSG_HEAD, resCode, len, ...data, 1, sumCheck(resCode, [...data, 1])]
	return msg
}

/**
 * 1、亮度设置
 * @param {int} light 0 到 100
 */
export function setLight(area, light) {
	if (light < 0 || light > 100) {
		throw new Error('亮度值只能在0-100')
	}
	let len = 2
	let msg = [MSG_HEAD, MSG_CODE.LIGHT, len, area, light, sumCheck(MSG_CODE.LIGHT, [area, light])]

	let resArr = resCheck(msg[1])
	console.log('发送正确的返回', resArr)
	sendMsg(msg)
}

/**
 * 2、设置速度
 * @param {int} area
 * @param {int} speed
 */
export function setSpeed(area, speed) {
	if (speed < 0 || speed > 100) {
		throw new Error('速度值只能在0-100')
	}
	let len = 2
	let msg = [MSG_HEAD, MSG_CODE.SPEED, len, area, speed, sumCheck(MSG_CODE.SPEED, [area, speed])]
	sendMsg(msg)
}

/**
 * 3、设置固定模式
 * @param {int} area
 * @param {int} mode
 */
export function setMode(area, mode) {
	let len = 2
	let msg = [MSG_HEAD, MSG_CODE.FIXED_MODE, len, area, mode, sumCheck(MSG_CODE.FIXED_MODE, [area, mode])]
	sendMsg(msg)
}


/**
 * 4、调试板模式
 * @param {int} area
 * @param {Object} color 颜色 {r:255,g:255,b:255}
 */
export function paletteMode(area, color) {
	let len = 4
	let msg = [MSG_HEAD, MSG_CODE.PALETTE,
		len, area, color.r, color.g, color.b,
		sumCheck(MSG_CODE.PALETTE, [area, color.r,
			color.g, color.b
		])
	]
	sendMsg(msg)
}

/**
 * 5、设置自定义模式
 * @param {int} area
 * @param {array} colors [{r:255,g:255,b:255}] 长度 最大 16
 * @param {int} mode
 */
export function setDiyMode(area, colors, mode) {
	let len = 7
	let clen = colors.length
	let msgs = [];
	for (let i = 0; i < clen; i++) {
		let msg = [MSG_HEAD,
			MSG_CODE.DIY_MODE,
			len, area, clen, i, mode, colors[i].r, colors[i].g, colors[i].b,
			sumCheck(MSG_CODE.DIY_MODE, [area, clen, i, mode, colors[i].r, colors[i].g, colors[i].b])
		];

		msgs.push(msg)
	}
	sendMsgs(msgs)
}

/**
 * 6、音律模式
 * @param {int} area
 * @param {array} colors [{r:255,g:255,b:255}] 长度 最大 16
 * @param {int} mode
 */
export function musicMode(area, colors, mode) {
	let len = 7
	let clen = colors.length
	let msgs = [];
	for (let i = 0; i < clen; i++) {
		let msg = [MSG_HEAD,
			MSG_CODE.MUSIC_MODE,
			len, area, clen, i, mode, colors[i].r, colors[i].g, colors[i].b,
			sumCheck(MSG_CODE.MUSIC_MODE, [area, clen, i, mode, colors[i].r, colors[i].g, colors[i].b])
		];

		msgs.push(msg)
	}
	sendMsgs(msgs)
}

/**
 * 7、设置咪头参数 音律模式下
 */
export function setMic(area, rate) {
	let len = 2
	let msg = [MSG_HEAD, MSG_CODE.MIC_SET,
		len, area, rate,
		sumCheck(MSG_CODE.MIC_SET, [area, rate])
	]
	sendMsg(msg)
}

/**
 * 8、外设开关
 */
export function deviceSwitch(device, onoff) {
	let len = 2
	let msg = [MSG_HEAD, MSG_CODE.DEVICE_SWITCH,
		len, device, onoff,
		sumCheck(MSG_CODE.DEVICE_SWITCH, [device, onoff])
	]
	sendMsg(msg)
}


/**
 * 9、RGB灯开关
 */
export function RGBSwitch(area, onoff) {
	let len = 2
	let msg = [MSG_HEAD, MSG_CODE.RGB_SWITCH,
		len, area, onoff,
		sumCheck(MSG_CODE.RGB_SWITCH, [area, onoff])
	]
	sendMsg(msg)
}

/**
 * 10 pwm设置
 */
export function setPWM(light, mode) {
	let len = 2
	if (light < 0 || light > 100) {
		throw new Error('亮度值只能在0-100')
	}
	let msg = [MSG_HEAD, MSG_CODE.SET_PWM,
		len, light, mode,
		sumCheck(MSG_CODE.SET_PWM, [light, mode])
	]
	sendMsg(msg)
}

/**
 * 11 打开对码
 */
export function openCode() {
	let len = 1
	let msg = [MSG_HEAD, MSG_CODE.OPEN_CODE,
		len, 0,
		sumCheck(MSG_CODE.OPEN_CODE, [0])
	]
	return sendMsg(msg)
}

/**
 * 关闭对码
 */
export function closeCode() {
	let len = 1
	let msg = [MSG_HEAD, MSG_CODE.CLOSE_CODE,
		len, 0,
		sumCheck(MSG_CODE.CLOSE_CODE, [0])
	]
	return sendMsg(msg)
}

/**
 * 字符串转化成二进制数据
 * @param {str} str
 */
export function str2ab(str) {
	let arr = new Uint8Array(str.length)
	for (let i = 0; i < str.length; i++) {
		arr[i] = str.charCodeAt(i)
	}
	return arr.buffer
}

export function arr2ab(arr) {
	let ab = new ArrayBuffer(arr.length)
	let dv = new DataView(ab)
	for (let i = 0; i < arr.length; i++) {
		dv.setUint8(i, arr[i])
	}

	return ab
}

/**
 * 二进制数据转化成字符串
 * @param {arrayBuffer} buf
 */
export function ab2str(buf) {
	let dv = new DataView(buf)
	let uint8 = new Uint8Array(buf.byteLength)
	let str = ''
	for (let i = 0; i < uint8.length; i++) {
		str += String.fromCharCode(dv.getUint8(i))
	}
	return str
}


export function ab2arr(buf) {
	let dv = new DataView(buf)
	let uint8 = new Uint8Array(buf.byteLength)
	let arr = []
	for (let i = 0; i < uint8.length; i++) {
		arr.push(dv.getUint8(i))
	}
	return arr
}


/**
 * 发送报文
 * @param {string} msg
 */
export function sendMsg(msg) {
	let ab = arr2ab(msg)
	return store.dispatch('bluetooth/sendMsg', ab)

}
/**
 * 发送报文 分包
 * @param {array} msgs
 */
export function sendMsgs(msgs) {


	try {
		msgs.forEach(async e => {
			await sendMsg(e)

			let resMsg = msgsCheck(e[1], [e[5]])

			console.log(store.state.bluetooth.notifyList, resMsg)
			let t1 = (new Date()).getTime()
			console.log(t1)
			let isTimeOut = false
			let timeOut = 1 // 1秒超时
			let str = resMsg.join('')
			while (!isTimeOut) {
				if (store.state.bluetooth.notifyList.indexOf(str) > -1) {
					console.log('校验通过')
					break
				} else {
					console.log('报文反馈验证未通过')
					throw new Error('分包发送失败')
				}
				isTimeOut = ((new Date()).getTime() - t1) > timeOut
			}
		})
	} catch (e) {
		console.log(e)
	}

}
